import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { PageModalService } from '../../shared/service/page-modal-service';
import { MyrealEstateComponent } from '../../coms/myreal-estate/myreal-estate.component';
import { ModalController, AlertController, IonContent } from '@ionic/angular';
import { HttpService } from '../../shared/service/http.service';
import { EventService } from 'src/app/shared/service/event.service';
declare let $: any;
@Component({
  selector: 'app-recommend-message',
  templateUrl: './recommend-message.component.html',
  styleUrls: ['./recommend-message.component.scss'],
})
export class RecommendMessageComponent implements OnInit {
  @Input() tagData: any;
  isLogin = false;
  idClass = '';
  private recommendBoxId: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private modalController: ModalController,
    public router: Router,
    private http: HttpService,
    private eventService: EventService
  ) { this.idClass = this.appGlobalService.getNowFormatDate(); }

  ngOnInit() {
    this.recommendBoxId = 'recommendBoxId' + new Date().getTime();
    // 应该判断loginAccount 因为退出app进程之后导致原来的参数loginParam为空 标签都不显示了。
    this.isLogin = localStorage.getItem("loginAccount") ? true : false;
  }


  // tslint:disable-next-line:use-life-cycle-interface
  ngAfterViewInit(): void {
    if (this.tagData.data && this.tagData.data.bgUrl !== undefined) {
      // 蜂喔赚钱宝 1.7.1 有配置背景图片的话则动态修改。
      setTimeout(() => {
        $('#' + this.recommendBoxId).css('background-image', 'url(' + this.tagData.data.bgUrl + ')');
      }, 500);

    }
  }


  // 按钮跳转
  go(obj, close?) {
    if (close) {
      if (document.getElementById('recommend-msg-cls')) {
        // tslint:disable-next-line:no-string-literal
        // document.getElementById('recommend-msg-cls')['style']['display'] = 'none';
        document.getElementById('recommend-msg-cls').style.display = 'none';
        return;
      }
    }
    if (obj.type === "page") {
      const pageParams = {
        pageId: obj.target,
        params: obj.params,
        sessionId: localStorage.getItem('sessionId')
      };
      console.log(pageParams);
      this.appGlobalService.goToForward(pageParams);
    } else if (obj.type === 'pageModal') {
      this.pageModalService.openPage(obj);
    } else if (obj.type === 'modal') {
      this.openRankingModal("myreal-estate", obj);
    } else if (obj.type === 'view') {
      // this.pageModalService.openPage(obj);
      // const newObj = modalData.data.itemdata.link.params;
      // Object.assign(newObj, { dateTime: new Date().getTime() });
      const param = {
        viewId: '1',
        params: obj.params,
        sessionId: localStorage.getItem('sessionId')
      };
      localStorage.setItem('needRefreshTab1', 'true');
      this.appGlobalService.goToForward(param);
    }
  }
  async openRankingModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.target,
      params: item.params
    };
    this.http.post('application/page', params, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: MyrealEstateComponent,
        componentProps: { tagData }
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
      try {
        // 返回传回的值，重新调用接口
        console.log(modalData);
        if (modalData.data.type !== undefined) {
          if (modalData.data.itemdata
            && modalData.data.itemdata.link
            && modalData.data.itemdata.link.params
            && modalData.data.itemdata.link.params.needRefreshParam) {
            // const currentParams = this.appGlobalService.getCurrentTarget();
            const targetObj = JSON.parse(localStorage.getItem('targetObj'));
            if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
              targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
              if (modalData.data.itemdata.link.params.opportunity_id) {
                targetObj.forward.params.opportunity_id = modalData.data.itemdata.link.params.opportunity_id;
              }
              localStorage.setItem('targetObj', JSON.stringify(targetObj));
            }
          }
          this.appGlobalService.reloadCurrentPage();
        } else {
          if (modalData.data.itemdata) {
            const newObj = modalData.data.itemdata.link.params;
            Object.assign(newObj, { dateTime: new Date().getTime() });
            const param = {
              viewId: '1',
              params: newObj ? newObj : {},
              sessionId: localStorage.getItem('sessionId')
            };
            console.log(param);
            localStorage.setItem('needRefreshTab1', 'true');
            this.appGlobalService.goToForward(param);
          }
        }

      } catch (error) {

      }

    });
  }
}
